package com.wwp.tbshop.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.squareup.picasso.Picasso;
import com.wwp.tbshop.R;
import com.wwp.tbshop.model.bean.CartAddBean;
import com.wwp.tbshop.model.bean.ProductDetailBean;
import com.wwp.tbshop.presenter.CartPresenter;
import com.wwp.tbshop.presenter.CollectionPresenter;
import com.wwp.tbshop.presenter.ProductDetailPresenter;
import com.wwp.tbshop.util.Constant;
import com.wwp.tbshop.util.PriceFormater;
import com.wwp.tbshop.util.SPUtils;
import com.wwp.tbshop.util.UiUtil;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

import static com.wwp.tbshop.R.id.bottomSheetLayout;

/**
 * Created by QIANG on 2017/6/15.
 */

public class ProductDetailActivity extends BaseActivity {
    @Bind(R.id.iv)
    ImageView mIv;
    @Bind(R.id.slider)
    SliderLayout mSlider;
    @Bind(R.id.good_new_price)
    TextView mGoodNewPrice;
    @Bind(R.id.good_old_price)
    TextView mGoodOldPrice;
    @Bind(R.id.good_rb_stars)
    RatingBar mGoodRbStars;
    @Bind(R.id.good_name)
    TextView mGoodName;
    @Bind(R.id.good_collection)
    ImageView mGoodCollection;
    @Bind(R.id.good_addcart)
    TextView mGoodAddcart;
    @Bind(R.id.good_buy)
    TextView mGoodBuy;
    @Bind(R.id.good_back)
    ImageButton mGoodBack;
    @Bind(R.id.good_cart)
    ImageButton mGoodCart;
    @Bind(bottomSheetLayout)
    BottomSheetLayout mBottomSheetLayout;
    @Bind(R.id.product_no_empty)
    ScrollView mNoEmpty;
    @Bind(R.id.product_empty)
    LinearLayout mEmpty;

    private View bottomSheet;
    private ImageView mClose;
    private ImageView mImg;
    private TextView mName;
    private TextView mPrice;
    private ImageButton mReduce;
    private TextView mNum;
    private ImageButton mAdd;
    private Button mSubmitBuy;
    private ProductDetailPresenter mProductDetailPresenter;
    private ProductDetailBean.ProductBean mPic;

    private RadioGroup mRgColor;
    private RadioGroup mRgSize;
    private RadioButton mColor1;
    private RadioButton mColor2;
    private RadioButton mSize1;
    private RadioButton mSize2;
    private RadioButton mSize3;

    private Bitmap mBitmap = null;
    private float mScaleWidth;
    private float mScaleHeight;


    private CartAddBean.CartBean mCartBean;
    private Button mSubmitCart;
    private Map<String, Integer> mProperty;
    private Context mContext;
    private CartPresenter mCartPresenter;
    private CollectionPresenter mCollectionPresenter;
    private String mUserId;
    private int productId;
    private int mPId;
    private boolean isCollected = true;

    public ProductDetailActivity() {
    }

    public ProductDetailActivity(CartPresenter cartPresenter) {
        mCartPresenter = cartPresenter;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void init() {
        super.init();

        processIntent();

    }

    private void processIntent() {

        if (getIntent() != null) {
            mPId = getIntent().getIntExtra("pId", 0);
            mProductDetailPresenter = new ProductDetailPresenter(this);
            mProductDetailPresenter.loadProductData(mPId);
        }

    }


    @OnClick({R.id.good_collection, R.id.good_addcart, R.id.good_buy, R.id.good_back, R.id.good_cart})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.good_collection:
                //收藏
                if (!isLoading()) {
                    Toast.makeText(UiUtil.getContext(), "要先登录哦,亲", Toast.LENGTH_SHORT).show();
                } else {
                    if (isCollected) {
                        addCollectionInfo();
                        mGoodCollection.setBackgroundResource(R.drawable.collection_selected);
                        isCollected = !isCollected;
                        Toast.makeText(UiUtil.getContext(), "收藏成功", Toast.LENGTH_SHORT).show();
                    } else {
                        addCollectionInfoError();
                        Toast.makeText(UiUtil.getContext(), "当前商品已经添加过收藏", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.good_addcart:
                //添加到购物车
                if (!isLoading()) {
                    Toast.makeText(UiUtil.getContext(), "要先登录哦,亲", Toast.LENGTH_SHORT).show();
                } else {
                    showOrCloseBuy();
                    mSubmitBuy.setVisibility(View.GONE);
                    mSubmitCart.setVisibility(View.VISIBLE);
                }

                break;
            case R.id.good_buy:
                //购买
                if (!isLoading()) {
                    Toast.makeText(UiUtil.getContext(), "要先登录哦,亲", Toast.LENGTH_SHORT).show();
                } else {
                    showOrCloseBuy();
                    mSubmitBuy.setVisibility(View.VISIBLE);
                    mSubmitCart.setVisibility(View.GONE);
                }
                break;
            case R.id.good_back:
                finish();
                break;
            case R.id.good_cart:
                Toast.makeText(UiUtil.getContext(), "跳转到购物车", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void addCollectionInfo() {
        //TODO:  mUserId要根据用户登录成功传过来的id

        mCollectionPresenter = new CollectionPresenter(this);
        mCollectionPresenter.addCollectionInfo(mUserId, mPId);

        Log.d("add", "mUserId: " + mUserId + "  productId: " + mPId);
    }

    public void addCollectionInfoError() {

    }

    private void showOrCloseBuy() {
        if (bottomSheet == null) {
            //加载要显示的布局
            bottomSheet = LayoutInflater.from(this).inflate(R.layout.bottom_sheet, (ViewGroup) getWindow().getDecorView(), false);

            //控件处理
            mClose = (ImageView) bottomSheet.findViewById(R.id.good_info_close);
            mImg = (ImageView) bottomSheet.findViewById(R.id.good_info_img);
            mName = (TextView) bottomSheet.findViewById(R.id.good_info_name);
            mPrice = (TextView) bottomSheet.findViewById(R.id.good_info_price);
            mRgColor = (RadioGroup) bottomSheet.findViewById(R.id.rg_color);
            mRgSize = (RadioGroup) bottomSheet.findViewById(R.id.rg_size);
            mColor1 = (RadioButton) bottomSheet.findViewById(R.id.good_info_color1);
            mColor2 = (RadioButton) bottomSheet.findViewById(R.id.good_info_color2);
            mSize1 = (RadioButton) bottomSheet.findViewById(R.id.good_info_size1);
            mSize2 = (RadioButton) bottomSheet.findViewById(R.id.good_info_size2);
            mSize3 = (RadioButton) bottomSheet.findViewById(R.id.good_info_size3);
            mReduce = (ImageButton) bottomSheet.findViewById(R.id.good_info_reduce);
            mNum = (TextView) bottomSheet.findViewById(R.id.good_info_num);
            mAdd = (ImageButton) bottomSheet.findViewById(R.id.good_info_add);
            mSubmitBuy = (Button) bottomSheet.findViewById(R.id.good_info_submit_buy);
            mSubmitCart = (Button) bottomSheet.findViewById(R.id.good_info_submit_cart);
            onClick();
            initData();
            initBigImage();
        }
        //判断BottomSheetLayout内容是否显示
        if (mBottomSheetLayout.isSheetShowing()) {
            //关闭内容显示
            mBottomSheetLayout.dismissSheet();
        } else {
            //显示BottomSheetLayout里面的内容
            mBottomSheetLayout.showWithSheetView(bottomSheet);
        }

    }

    private void initData() {
        mProperty = new HashMap<>();
        mProperty.put(mPic.getProductProperty().get(0).getV(), mPic.getProductProperty().get(0).getId());
        mProperty.put(mPic.getProductProperty().get(1).getV(), mPic.getProductProperty().get(1).getId());
        mProperty.put(mPic.getProductProperty().get(2).getV(), mPic.getProductProperty().get(2).getId());
        mProperty.put(mPic.getProductProperty().get(3).getV(), mPic.getProductProperty().get(3).getId());
        mProperty.put(mPic.getProductProperty().get(4).getV(), mPic.getProductProperty().get(4).getId());


        Picasso.with(UiUtil.getContext()).load(Constant.HOST + mPic.getPics().get(0)).into(mImg);
        mName.setText(mPic.getName());
        mPrice.setText(PriceFormater.format(mPic.getPrice()));
        mColor1.setText(mPic.getProductProperty().get(0).getV());
        mColor2.setText(mPic.getProductProperty().get(1).getV());
        mSize1.setText(mPic.getProductProperty().get(2).getV());
        mSize2.setText(mPic.getProductProperty().get(3).getV());
        mSize3.setText(mPic.getProductProperty().get(4).getV());
    }

    private void onClick() {
        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOrCloseBuy();
            }
        });

        mAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addOperation();
            }
        });
        mReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reduceOperation();
            }
        });

        mRgColor.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == mColor1.getId()) {
                    mColor1.setBackgroundResource(R.drawable.shape_selected_bg);
                    mColor2.setBackgroundResource(R.drawable.shape_normal_bg);
                } else {
                    mColor2.setBackgroundResource(R.drawable.shape_selected_bg);
                    mColor1.setBackgroundResource(R.drawable.shape_normal_bg);
                }
            }
        });
        mRgSize.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == mSize1.getId()) {
                    mSize1.setBackgroundResource(R.drawable.shape_selected_bg);
                    mSize2.setBackgroundResource(R.drawable.shape_normal_bg);
                    mSize3.setBackgroundResource(R.drawable.shape_normal_bg);
                } else if (checkedId == mSize2.getId()) {
                    mSize2.setBackgroundResource(R.drawable.shape_selected_bg);
                    mSize1.setBackgroundResource(R.drawable.shape_normal_bg);
                    mSize3.setBackgroundResource(R.drawable.shape_normal_bg);
                } else {
                    mSize3.setBackgroundResource(R.drawable.shape_selected_bg);
                    mSize1.setBackgroundResource(R.drawable.shape_normal_bg);
                    mSize2.setBackgroundResource(R.drawable.shape_normal_bg);
                }
            }
        });

        mImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIv.setVisibility(View.VISIBLE);
                Matrix matrix = new Matrix();
                matrix.postScale(mScaleWidth, mScaleHeight);

                Bitmap newBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
                mIv.setImageBitmap(newBitmap);
            }
        });
        mIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIv.setVisibility(View.GONE);
            }
        });

        mSubmitCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int colorId = mRgColor.getCheckedRadioButtonId();
                int sizeId = mRgSize.getCheckedRadioButtonId();
                if (colorId == -1 || sizeId == -1) {
                    Toast.makeText(UiUtil.getContext(), "亲,请选择颜色和尺寸大小", Toast.LENGTH_SHORT).show();
                    return;
                }
                String size = ((RadioButton) findViewById(sizeId)).getText().toString();


                //TODO:添加到数据库的数据

                productId = mPic.getId();
                String productCount = mNum.getText().toString();
                int propertyId = mProperty.get(size);

                //TODO:添加到数据库
                mCartPresenter = new CartPresenter((ProductDetailActivity) mContext);
                mCartPresenter.addCartInfo(mUserId, productId + "", productCount, propertyId + "");
                showOrCloseBuy();
                Toast.makeText(UiUtil.getContext(), "加入成功", Toast.LENGTH_SHORT).show();
            }
        });

        mSubmitBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int colorId = mRgColor.getCheckedRadioButtonId();
                int sizeId = mRgSize.getCheckedRadioButtonId();
                if (colorId == -1 || sizeId == -1) {
                    Toast.makeText(UiUtil.getContext(), "亲,请选择颜色和尺寸大小", Toast.LENGTH_SHORT).show();
                    return;
                }
                //TODO:获取购买的数据
                String color = ((RadioButton) findViewById(colorId)).getText().toString();
                String size = ((RadioButton) findViewById(sizeId)).getText().toString();
                String num = mNum.getText().toString();

                //TODO:跳转到结算中心
                Intent payIntent = new Intent(bottomSheet.getContext(), OrderSubmitActivity.class);
                startActivity(payIntent);
                Toast.makeText(UiUtil.getContext(), "colorId=" + color + "  sizeId=" + size + " num=" + num, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initBigImage() {
        DisplayMetrics dm = new DisplayMetrics();//创建矩阵
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        mBitmap = getBitmap(Constant.HOST + mPic.getPics().get(0));
        int width = mBitmap.getWidth();
        int height = mBitmap.getHeight();
        int w = dm.widthPixels; //得到屏幕的宽度
        int h = dm.heightPixels; //得到屏幕的高度

        Log.d("bitmap", "宽度" + width + "----" + w);
        Log.d("bitmap", "高度" + height + "----" + h);
        mScaleWidth = ((float) w) / width;
        mScaleHeight = ((float) h) / height;
        mImg.setImageBitmap(mBitmap);
    }

    public Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    int count = 0;

    private void addOperation() {
        count = Integer.parseInt((String) mNum.getText());
        count++;
        mNum.setText(count + "");
        Log.d("product", "addOperation " + count);
    }

    private void reduceOperation() {
        count = Integer.parseInt((String) mNum.getText());
        count--;
        if (count < 1) {
            count = 1;
            Toast.makeText(UiUtil.getContext(), "不能再少了,亲", Toast.LENGTH_SHORT).show();
        }
        mNum.setText(count + "");
        Log.d("product", "reduceOperation " + count);

    }


    public void onProductSuccess(ProductDetailBean.ProductBean pic) {
        if (pic.getPics().size() == 0) {
            mEmpty.setVisibility(View.VISIBLE);
            mNoEmpty.setVisibility(View.GONE);
        } else {
            mEmpty.setVisibility(View.GONE);
            mNoEmpty.setVisibility(View.VISIBLE);
            this.mPic = pic;
            //轮播图
            List<String> pics = pic.getPics();
            for (int i = 0; i < pics.size(); i++) {
                TextSliderView textSliderView = new TextSliderView(this);
                Log.d("url", Constant.HOST + pics.get(i));
                textSliderView.image(Constant.HOST + pics.get(i));
                mSlider.addSlider(textSliderView);
            }
            mGoodNewPrice.setText(PriceFormater.format(pic.getPrice()));
            mGoodOldPrice.setText(PriceFormater.format(pic.getMarketPrice()));
            mGoodOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            mGoodRbStars.setRating(pic.getScore());
            mGoodName.setText(pic.getName());
        }
    }

    // 是否已登录
    public boolean isLoading() {
        mUserId = SPUtils.getUerid();
        if (TextUtils.isEmpty(mUserId)) {
            return false;
        }
        return true;
    }

}
